//
//  JXNetworkTool.swift
//  01-weiboSwift
//
//  Created by TwistFate on 16/2/27.
//  Copyright © 2016年 TwistFate. All rights reserved.
//

import UIKit
import AFNetworking

enum JXNetworkError : Int {
    case accessTokenEmpty = -1
    case uidEmpty = -2
    
    var errorMessage : String {
        get {
            switch self {
            case accessTokenEmpty : return "accessToken没有值"
            case uidEmpty : return "uid没有值"
            }
        }
    }
    
    func error () -> NSError {
        return NSError(domain: "net", code: self.rawValue, userInfo: ["access_token" : self.errorMessage])
    }
}

class JXNetworkTool: NSObject {
    
    
    let afnManager: AFHTTPSessionManager

    static let sharedInstance : JXNetworkTool = JXNetworkTool()
    
    //让init成为私有方法,确保外界使用网络单列
    private override init() {
        let url = NSURL(string: "https://api.weibo.com/")
        afnManager = AFHTTPSessionManager(baseURL: url)
        
//        self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil];
        afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        super.init()
    }
    
    //MARK: - 授权相关
    
    let client_id = "1896760231"
    let client_secret = "40eb200d5eed72b2f6d469b4ab91cbb1"
    let redirect_uri = "http://www.baidu.com/"
    let oauthUrl = "https://api.weibo.com/oauth2/authorize"
    
    func oauthLoginUrl () -> NSURL {
        let oauthLoginUrl :String = oauthUrl + "?" + "client_id=" + client_id + "&" + "redirect_uri=" + redirect_uri
        return NSURL(string: oauthLoginUrl)!
    }
    
    func loadAccessToken (code :String , accessTokenFinished :(response : [String : AnyObject]? ,error : NSError?) ->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameter = [
            "client_id" : client_id,
            "client_secret" : client_secret,
            "grant_type " : "authorization_code",
            "code" : code,
            "redirect_uri" : redirect_uri
        ]
        
        afnManager.POST(urlString, parameters: parameter, progress: nil, success:
            { (_, response) -> Void in
//                print("AccessToken授权时response : \(response)")
                  let dict = response as? [String : AnyObject]
                accessTokenFinished(response: dict , error: nil)
            }) { (_, error) -> Void in
                print("AccessToken授权时error : \(error)")
                accessTokenFinished(response: nil, error: error)
                
        }
    }
    
    func loadUserInfo (finished :(result :[String : AnyObject]? ,error : NSError?) ->()) {
//        JXUserAcountViewModel.sharedInstance.userAcount?.access_token = nil
        guard let access_token = JXUserAcountViewModel.sharedInstance.userAcount?.access_token else {
            
            let error = JXNetworkError.accessTokenEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        guard let uid = JXUserAcountViewModel.sharedInstance.userAcount?.uid else {
            
            let error = JXNetworkError.uidEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        let urlString = "https://api.weibo.com/2/users/show.json"
        let parameter = ["access_token" : access_token , "uid" : uid]
        
        afnManager.GET(urlString, parameters: parameter, progress: nil, success: { (_, result) -> Void in
            finished(result: result as? [String : AnyObject] , error: nil)
            }) { (_, error) -> Void in
                finished(result: nil , error: error)
        }
    }
    
    func loadStatus (finished :(result :[String : AnyObject]? ,error : NSError?) ->()) {
        guard let access_token = JXUserAcountViewModel.sharedInstance.userAcount?.access_token else {
            
            let error = JXNetworkError.accessTokenEmpty.error()
            finished(result: nil, error: error)
            return
        }
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let parameter = ["access_token" : access_token]
        
        afnManager.GET(urlString, parameters: parameter, progress: nil, success: { (_, result) -> Void in
            finished(result: result as? [String : AnyObject] , error: nil)
            }) { (_, error) -> Void in
                finished(result: nil, error: error)
        }
    }
    
}
